<template>
  <div v-if="dirName" class="Upload">
    <!--    //展示文件列表-->
    <ul v-if="showFileList" class="el-upload-list el-upload-list--picture-card">
      <vuedraggable
        v-model="fileList"
        :options="{ sort: sort, filter: '.undraggable' }"
        class="wrapper clearfix"
        @end="fileChangeHandle()"
      >
        <template v-for="(item,index) in fileList">
          <li :key="index" class="el-upload-list__item is-success">
            <span
              v-if="item.name&&canWmv(item.name,'wmv')"
              style="width: 100%;height: 100%;display: inline-block;text-align: center;line-height: 10;background-color: #eee;"
            >WMV视频</span>
            <template v-if="item.status !== '0' && item.save_url">
              <img
                v-if="getFileShowType(item.save_url) === 'img'"
                :src="item.save_url"
                class="el-upload-list__item-thumbnail"
              >
              <video
                v-else-if="getFileShowType(item.save_url) === 'video'"
                :src="item.save_url"
                style="width: 100%"
              />
              <div
                v-else
                class="el-upload-list__item-thumbnail"
                style="display: flex;justify-content: center;align-items: center"
              >
                <i class="hmt-copy" style="font-size: 80px" />
              </div>
            </template>
            <span class="el-upload-list__item-actions">
              <span
                v-if="getFileShowType(item.save_url)"
                class="el-upload-list__item-preview"
                @click="previewFile(item)"
              >
                <i class="el-icon-zoom-in" />
              </span>
              <span
                v-else
                class="el-upload-list__item-preview"
                @click="downLoadFile(item)"
              >
                <i class="hmt-down" style="color: #fff" />
              </span>
              <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(index)">
                <i class="el-icon-delete" />
              </span>
            </span>
            <el-progress v-if="item.status === '0'" :percentage="item.percentage" type="circle" />
          </li>
        </template>
        <li v-if="fileList.length < limit&& !disabled" class="el-upload-list__item btns undraggable">
          <div tabindex="0" class="el-upload el-upload--picture-card" @click="handleClick">
            <i class="el-icon-plus" />
            <input
              ref="input"
              :accept="acceptValue"
              :multiple="multiple"
              type="file"
              name="file"
              class="el-upload__input"
              @change="handleChange"
            >
          </div>
        </li>
      </vuedraggable>
    </ul>
    <!--    //不展示文件列表-->
    <div v-else>
      <li
        v-if="fileList.length < limit&& !disabled"
        class="el-upload-list__item btns undraggable"
      >
        <div tabindex="0" class="el-upload el-upload--picture-card" @click="handleClick">
          <i class="el-icon-plus" />
          <input
            ref="input"
            :accept="acceptValue"
            :multiple="multiple"
            type="file"
            name="file"
            class="el-upload__input"
            @change="handleChange"
          >
        </div>
      </li>
    </div>
    <el-dialog :modal="false" :visible.sync="dialogImgVisible" append-to-body>
      <img :src="dialogImageUrl" width="100%" alt>
    </el-dialog>
    <el-dialog :modal="false" :visible.sync="dialogVideoVisible" append-to-body @close="videoClose">
      <video ref="video" :style="{ width: '100%', height: '500px' }" :src="dialogVideoUrl" controls="controls" />
    </el-dialog>
  </div>
</template>

<script>
import { uploads } from '@/api/index.js'
import vuedraggable from 'vuedraggable'
export default {
  name: 'Upload',
  components: { vuedraggable },
  props: {
    /** 文件夹名称 */
    dirName: {
      type: String,
      default: ''
    },
    // 是否可多选
    multiple: {
      type: Boolean,
      default: false
    },
    // 隐藏上传按钮
    disabled: {
      type: Boolean,
      default: false
    },
    // 限制上传数量
    limit: {
      type: Number,
      default: 999
    },
    // 文件列表
    fileList: {
      type: Array, //                    状态0 上传中
      default: () => [] //  {save_url:'',url:'',status:'0',percentage:4}
    },
    // 上传文件类型限制    listType=img accept=imgAccept   listType=video accept=videoAccept
    accept: {
      type: String,
      default: ''
    },
    // 文件列表展示类型
    listType: {
      type: String,
      default: '*' // img video
    },
    // 上传文件大小限制
    size: {
      type: Number,
      default: 1024 * 1024 * 20 // 默认20M       2097152 = 2M
    },
    // 是否显示已上传文件列表
    showFileList: {
      type: Boolean,
      default: true
    },
    sort: {
      type: Boolean,
      default: true
    },
    uploadFetch: {
      type: Function,
      default: null
    }
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVideoUrl: '',
      dialogImgVisible: false,
      dialogVideoVisible: false,
      previewList: [],
      vPlayerType: '', // video img
      videoAccept:
        'audio/mp4,video/mp4,application/ogg,audio/ogg,video/quicktime,video/3gpp,audio/x-ms-wmv,video/x-ms-wmx',
      imgAccept: 'image/jpeg,image/png,image/gif'
    }
  },
  computed: {
    acceptValue() {
      if (this.accept) return this.accept
      if (this.listType === 'img') return this.imgAccept
      if (this.listType === 'video') return this.videoAccept
    }
  },
  methods: {
    /*
     * 下载文件
     */
    downLoadFile(item) {
      const anchor = document.createElement('a')
      if ('download' in anchor) {
        anchor.style.visibility = 'hidden'
        anchor.href = item.save_url
        anchor.download = ''
        document.body.appendChild(anchor)
        const evt = document.createEvent('MouseEvents')
        evt.initEvent('click', true, true)
        anchor.dispatchEvent(evt)
        document.body.removeChild(anchor)
      } else {
        throw new Error('upload 下载文件异常')
      }
    },
    previewFile(file) {
      if (this.getFileShowType(file.save_url) === 'video') {
        this.dialogVideoUrl = file.url
        this.dialogVideoVisible = true
      }
      if (this.getFileShowType(file.save_url) === 'img') {
        this.dialogImageUrl = file.url ? file.url : file.save_url
        this.dialogImgVisible = true
      }
    },
    // 关闭video
    videoClose() {
      this.$refs.video.pause && this.$refs.video.pause()
    },
    canWmv(url, fileType) {
      const ext = url.split('.').pop()
      return ext === fileType
    },
    getFileType(type) {
      switch (type) {
        case 'image/jpeg':
          return 'img'
        case 'image/png':
          return 'img'
        case 'image/gif':
          return 'img'
        case 'video/mp4':
          return 'video'
        case 'video/ogg':
          return 'video'
        case 'video/quicktime':
          return 'video'
        case 'video/3gpp':
          return 'video'
        case 'video/x-ms-wmv':
          return 'video'
        default:
          return ''
      }
    },
    /* 获取文件展示类型
     * 从文件url 判断文件 是图片还是视频
     * @param {String} url 文件路径
     * @return {String}
     */
    getFileShowType(url) {
      if (!url) return
      const type = url.split('.').pop()
      const wxtype = url.split('?').pop()
      if (['jpeg', 'png', 'gif', 'jpg'].includes(type) ||
        ['wx_fmt=png', 'wx_fmt=jpeg', 'wx_fmt=gif', 'wx_fmt=jpg'].includes(wxtype) ||
        url.indexOf('data:image/png;') === 0
      ) {
        return 'img'
      } else if (['mp4', 'ogg', 'mov', '3gpp'].includes(type)) {
        return 'video'
      }
    },
    fileChangeHandle(type) {
      this.$emit('update:fileList', this.fileList)
      this.$emit('change', this.fileList, type)
    },
    // 删除
    handleRemove(index) {
      const _this = this
      console.log( _this.$task, '---------删除成功-----------------')
      this.$confirm('此操作将删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        _this.fileList.splice(index, 1)
        _this.fileChangeHandle('delete')
        _this.$task({
          type: 'success',
          message: '删除成功!'
        })
        _this.$forceUpdate()
      })
    },
    handleChange(ev) {
      const files = ev.target.files
      if (!files) return
      this.uploadFiles(files)
    },

    uploadFiles(files) {
      if (this.limit && this.fileList.length + files.length > this.limit) return
      let postFiles = [...files]
      if (!this.multiple) {
        postFiles = postFiles.slice(0, 1)
      }
      if (postFiles.length === 0) return

      postFiles.forEach(rawFile => {
        if (rawFile) {
          const file = {
            status: '0',
            name: rawFile.name,
            size: rawFile.size,
            type: rawFile.type,
            ext: this.getFileType(rawFile.type),
            percentage: 0,
            uid: Date.now() + this.fileList.length + 1,
            raw: rawFile,
            index: this.fileList.length
          }
          if (['img', 'video'].includes(this.getFileType(rawFile.type))) {
            file.url = URL.createObjectURL(rawFile)
          }
          this.fileList.push(file)
          this.post(file)
        }
      })
    },
    // 上传
    post(rawFile) {
      const options = {
        file: rawFile.raw,
        uid: rawFile.uid,
        onProgress: e => {
          this.onProgress(e, rawFile)
        },
        onSuccess: res => {
          this.onSuccess(res, rawFile)
        },
        onError: err => {
          this.onError(err, rawFile)
        },
        dirname: this.dirName
      }
      if (rawFile.size <= this.size) {
        uploads(options)
          .then(url => {
            console.log(url)
            options.onSuccess(url, rawFile)
            this.uploadFetch && this.uploadFetch(rawFile.raw)
          })
          .catch(e => {
            options.onError(e, rawFile)
          })
      } else {
        if (this.size >= 1024 * 1024) {
          const size = this.$Divide(this.$Divide(this.size, 1024), 1024)
          this.$task.error(`请上传${size.toFixed(1)}M以内的文件！`)
        } else {
          const size = this.$Divide(this.size, 1024)
          this.$task.error(`请上传${size}K以内的文件！`)
        }
        options.onError(null, rawFile)
      }
    },
    onProgress(e, rawFile) {
      // rawFile.percentage = (e.percent * 100).toFixed(2) || 0
      rawFile.percentage = e.percent || 0
      this.fileList.splice(rawFile.index, 1, rawFile)
    },
    onSuccess(url, rawFile) {
      rawFile.save_url = url
      rawFile.status = '1'
      this.fileList.splice(rawFile.index, 1, { ...rawFile })
      this.fileChangeHandle()
      this.$forceUpdate()
    },
    onError(err, rawFile) {
      this.fileList.splice(rawFile.index, 1)
    },
    handleClick() {
      if (!this.disabled) {
        this.$refs.input.value = null
        this.$refs.input.click()
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.Upload {
  .el-upload-list__item.btns {
    border: none;
  }
  .el-upload--picture-card {
    line-height: 148px!important;
  }
  .hidden .el-upload.el-upload--picture-card {
    display: none;
  }
}
</style>
